<?php

/**
 * 
 *  将new从类外移至类内 在类的外面不需要new
 *  PGDB::getInstance();
 *  单例模式 ( PGDB 数据库类 )
 * 
 * */

class PGDB
{

    protected $conn = null;
    static protected $ins = null;

    final protected function __construct(array $dbconfig = array())
    {
        $this->_db_config  = [
            'DB_HOST' => 'host=10.28.1.172',
            'DB_PORT' => 'port=5400',
            'DB_NAME' => 'dbname=xialj',
            'DB_CREDENTIALS' => 'user=usr_cloudtop password=usr@Cloudtop_2018',
        ] ?? $dbconfig;
        $connect_str = $this->_db_config['DB_HOST'] . ' ' . $this->_db_config['DB_PORT'] . ' ';
        $connect_str .= $this->_db_config['DB_NAME'] . ' ' . $this->_db_config['DB_CREDENTIALS'];
        $this->conn = pg_connect($connect_str);
    }

    /**
     * 单例模式的创建对象方法
     */
    static public function getInstance(array $dbconfig = array()): PGDB
    {
        if (self::$ins instanceof self) {
            return self::$ins;
        }
        self::$ins = new self($dbconfig);
        return self::$ins;
    }

    /**
     * 在外部获取数据库连接的方法
     */
    public function getDBConnect()
    {
        return $this->conn;
    }

    /**
     * 用于执行SQL语句的方法
     * @param string sql 填写自己的数据库配置方法
     * @return 查询/删除/修改/增加 的结果
     */
    public function query(string $sql)
    {
        return pg_query($this->getDbConnect(), $sql);
    }
}
